package com.splic.product.service.impl.thirdRequest;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.splic.common.utils.DateUtils;
import com.splic.common.utils.StringUtils;
import com.splic.product.domain.TodayInHistory;
import com.splic.product.dto.TodayInHistoryRequestDto;
import com.splic.product.service.ThirdRequestDataService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.List;

/**
 * ==========================
 * 开发：singe
 * 创建时间：2022-02-28 22:11
 * 版本: 1.0
 * 描述：TODO
 * ==========================
 */
@Slf4j
@Service
public class TodayInHistoryRequestServiceImpl implements ThirdRequestDataService {


    private final static String key = "27358a5ca733310aeaee508646f29353";
    private final static String url = "http://v.juhe.cn/todayOnhistory/queryEvent.php?key="+key+"&date=";
    @Autowired
    private RestTemplate restTemplate;

    @Override
    public TodayInHistoryRequestDto requestThirdData() {
        String result = restTemplate.getForObject(url+ DateUtils.parseDateToStr("M/d",new Date()),String.class);
        if (StringUtils.isEmpty(result)) {
            log.error("获取历史上的今天数据失败");
            return null;
        }
        Date curentDate = new Date();
        List<TodayInHistory> todayInHistoryList = Lists.newArrayList();
        JSONObject resultObject = JSONObject.parseObject(result);
        if (resultObject != null && StringUtils.equals("success",resultObject.getString("reason"))) {
            JSONArray array = resultObject.getJSONArray("result");
            TodayInHistory rate =null;
            for(Object object :array){
                JSONObject jsonObject = JSONObject.parseObject(object.toString());
                rate = new TodayInHistory();
                rate.setDate(curentDate);
                rate.setDateDesc(jsonObject.getString("date"));
                rate.setTitle(jsonObject.getString("title"));
                todayInHistoryList.add(rate);
            }
        }
        TodayInHistoryRequestDto dto = new TodayInHistoryRequestDto();
        dto.setTodayInHistoryList(todayInHistoryList);
        return dto;
    }

}
